package com.ai.imagetext.controller;

import com.ai.imagetext.config.AliOSSManager;
import com.ai.imagetext.dto.ImageDTO;
import com.ai.imagetext.entity.Image;
import com.ai.imagetext.service.FileUploadService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/api/upload")
@RequiredArgsConstructor
@Tag(name = "文件上传", description = "文件上传相关的API接口")
public class FileUploadController {
    
    private final FileUploadService fileUploadService;
    
    /**
     * 单文件上传
     */
    @Operation(summary = "单文件上传", description = "上传单个图片文件")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "上传成功"),
        @ApiResponse(responseCode = "400", description = "上传失败")
    })
    @PostMapping("/single")
    public ResponseEntity<Map<String, Object>> uploadSingle(
            @Parameter(description = "要上传的图片文件", required = true) 
            @RequestParam("file") MultipartFile file) {
        log.info("Received single file upload request: {}", file.getOriginalFilename());
        
        try {
            Image image = fileUploadService.uploadSingleFile(file);
            ImageDTO imageDTO = convertToDTO(image);
            Map<String, Object> response = createSuccessResponse("文件上传成功");
            response.put("data", imageDTO);
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("Single file upload failed", e);
            return ResponseEntity.badRequest().body(createErrorResponse(e.getMessage()));
        }
    }
    
    /**
     * 批量文件上传
     */
    @Operation(summary = "批量文件上传", description = "批量上传多个图片文件")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "批量上传成功"),
        @ApiResponse(responseCode = "400", description = "批量上传失败")
    })
    @PostMapping("/batch")
    public ResponseEntity<Map<String, Object>> uploadBatch(
            @Parameter(description = "要上传的图片文件列表", required = true) 
            @RequestParam("files") List<MultipartFile> files) {
        log.info("Received batch file upload request: {} files", files.size());
        
        try {
            List<Image> images = fileUploadService.uploadMultipleFiles(files);
            List<ImageDTO> imageDTOs = images.stream()
                    .map(this::convertToDTO)
                    .collect(Collectors.toList());
            
            Map<String, Object> response = createSuccessResponse("批量上传成功");
            response.put("data", imageDTOs);
            response.put("count", imageDTOs.size());
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("Batch file upload failed", e);
            return ResponseEntity.badRequest().body(createErrorResponse(e.getMessage()));
        }
    }
    
    /**
     * 删除文件
     */
    @PostMapping("/delete/{imageId}")
    public ResponseEntity<Map<String, Object>> deleteFile(@PathVariable Long imageId) {
        log.info("Received file delete request: imageId={}", imageId);
        try {
            boolean deleted = fileUploadService.deleteFile(imageId);
            Map<String, Object> response = createSuccessResponse("文件删除成功");
            response.put("deleted", deleted);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("File delete failed", e);
            return ResponseEntity.badRequest().body(createErrorResponse(e.getMessage()));
        }
    }
    
    /**
     * 获取文件信息
     */
    @GetMapping("/info/{imageId}")
    public ResponseEntity<Map<String, Object>> getFileInfo(@PathVariable Long imageId) {
        try {
            Image image = fileUploadService.getFileInfo(imageId);
            ImageDTO imageDTO = convertToDTO(image);
            Map<String, Object> response = createSuccessResponse("获取文件信息成功");
            response.put("data", imageDTO);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("Get file info failed", e);
            return ResponseEntity.badRequest().body(createErrorResponse(e.getMessage()));
        }
    }
    
    /**
     * 获取上传统计信息
     */
    @GetMapping("/statistics")
    public ResponseEntity<Map<String, Object>> getUploadStatistics() {
        try {
            FileUploadService.UploadStatistics stats = fileUploadService.getUploadStatistics();
            Map<String, Object> response = createSuccessResponse("获取统计信息成功");
            response.put("data", stats);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("Get upload statistics failed", e);
            return ResponseEntity.badRequest().body(createErrorResponse(e.getMessage()));
        }
    }
    
    /**
     * 检查文件是否存在
     */
    @GetMapping("/exists")
    public ResponseEntity<Map<String, Object>> checkFileExists(@RequestParam String filePath) {
        try {
            boolean exists = fileUploadService.fileExists(filePath);
            Map<String, Object> response = createSuccessResponse("检查文件存在性成功");
            response.put("exists", exists);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("Check file exists failed", e);
            return ResponseEntity.badRequest().body(createErrorResponse(e.getMessage()));
        }
    }
    
    /**
     * 转换为DTO
     */
    private ImageDTO convertToDTO(Image image) {
        ImageDTO dto = new ImageDTO();
        dto.setId(image.getId());
        dto.setName(image.getName());
        dto.setOriginalName(image.getOriginalName());
        dto.setFileUrl(image.getFileUrl());
        dto.setFileSize(image.getFileSize());
        dto.setMimeType(image.getMimeType());
        dto.setWidth(image.getWidth());
        dto.setHeight(image.getHeight());
        dto.setDescription(image.getDescription());
        dto.setAiRecognitionStatus(image.getAiRecognitionStatus());
        dto.setCreatedAt(image.getCreatedAt());
        dto.setUpdatedAt(image.getUpdatedAt());
        dto.setUsageCount(image.getUsageCount());
        
        // 解析标签
        if (image.getTags() != null && !image.getTags().isEmpty()) {
            dto.setTags(List.of(image.getTags().split(",")));
        }
        
        return dto;
    }
    
    /**
     * 创建成功响应
     */
    private Map<String, Object> createSuccessResponse(String message) {
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", message);
        response.put("timestamp", System.currentTimeMillis());
        return response;
    }
    
    /**
     * 创建错误响应
     */
    private Map<String, Object> createErrorResponse(String message) {
        Map<String, Object> response = new HashMap<>();
        response.put("success", false);
        response.put("message", message);
        response.put("timestamp", System.currentTimeMillis());
        return response;
    }
}